import React from 'react';
import { connect } from 'dva'
import queryString from 'query-string'
import {
  Button,
  Card,
  Modal,
  Tabs
} from 'antd'
import List from "./List";
import PageHeaderLayout from 'components/Layout/PageHeaderLayout';
import OrderFilterUnExpand from 'components/Filter/OrderFilterUnExpand';
import styles from './List.less';
import { showButton } from 'utils/promissionFilter'

const FinancialSettlementApplies = ({ location, dispatch, financialSettlementApply, app, loading }) => {
  location.query = queryString.parse(location.search);
  const { items, pagination, selectRows, isExpand, selectedRowKeys ,currentType} = financialSettlementApply;
  const { user, resources } = app
  const TabPane = Tabs.TabPane;
  const breadcrumbList = [
    {
      title: '财务管理'
    }, {
      title: '财务结算'
    }
  ];

  const listProps = {
    dataSource: items,
    loading: loading.effects['financialSettlementApply/query'],
    pagination,
    pageChangeAction: 'financialSettlementApply/query',
    dispatch,
    location,
    selectedRowKeys,
    onShowDetail(record) {
      dispatch({
        type: 'financialSettlementApply/showDetail',
        payload: {
          recordId: record.id
        }
      });
    },
    onSelectRows(selectedRowKeys, selectRows) {
      dispatch({
        type: 'financialSettlementApply/onSelectChange',
        payload: {
          selectRows: selectRows,
          selectedRowKeys: selectedRowKeys
        }
      });
    }
  };

  // 定义筛选属性 表单相关
  const filterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'orderId',
        title: '单据编号'
      }, {
        type: 'select',
        id: 'businessType',
        title: '业务类型',
        options: [
          {
            value: "",
            name: '全部'
          },
          // , {
          //   value: 'PERCENTAGE',
          //   name: '提成'
          // },
          //  {
          //   value: 'WITHHOLD',
          //   name: '扣款'
          // },
          {
            value: 'PLACE_ORDER',
            name: '下单'
          },
          {
            value: 'BALANCE_CHARGE',
            name: '余额变更调增'
          },
          {
            value: 'BALANCE_WITHHOLD',
            name: '余额变更调减'
          },
          {
            value: 'CHANGE',
            name: '调账'
          },
          {
            value: 'CONTRACTCHANGE',
            name: '合同变更'
          },
          {
            value: 'COUPONS',
            name: '优惠券'
          },
          {
            value: 'PAY_FOR_UNPAID',
            name: '待交尾款'
          },
          {
            value: 'PROFITS_DISTRIBUTION',
            name: '分润'
          },
          {
            value: 'CANCEL_ORDER',
            name: '取消'
          },
          // {
          //   value: 'COMPENSATION',
          //   name: '补差'
          // },
          //  {
          //   value: 'CHARGE',
          //   name: '充值'
          // },
          // {
          //   value: 'AFTERSALE_COMPENSATION',
          //   name: '售后赔偿'
          // }, {
          //   value: 'AFTERSALE_BUSINESSREFUND',
          //   name: '商家退款'
          // }
        ]
      }, {
        type: 'select',
        id: 'settlementStatus',
        title: '结算状态',
        options: [
          {
            value: '',
            name: '全部'
          },
          {
            value: 'NULL',
            name: '未结算'
          }, {
            value: 'SETTLE_SUCCESS',
            name: '已结算'
          },  {
            value: 'SETTLE_LOCK',
            name: '已锁定'
          },{
            value: 'SETTLE_FAIL',
            name: '结算失败'
          }
        ]
      }, {
        type: 'input',
        id: 'distributorName',
        title: '门店名称'
      }, {
        type: 'input',
        id: 'userName',
        title: '下单人'
      }, {
        type: 'dateRule',
        id: 'createTime',
        dateFormat: 'YYYY/MM/DD HH:mm:ss',
        title: '创建时间'
      }, {
        type: 'dateRule',
        id: 'handleTime',
        dateFormat: 'YYYY/MM/DD HH:mm:ss',
        title: '结算时间'
      }, {
        type: 'input',
        id: 'settlementAmount',
        title: '金额'
      }
    ],
    onFilterChange(value) {
      dispatch({
        type: 'financialSettlementApply/query',
        payload: {
          ...value
        }
      })
    },
    isExpand,
    noExpand() {
      dispatch({ type: 'financialSettlementApply/unExpandFilter', payload: {} })
    },
    expand() {
      dispatch({ type: 'financialSettlementApply/expandFilter', payload: {} })
    }
  }

  /**
   * 结算
   * @param {} selectRows
   */
  const doSettlement = (selectRows) => {
    if (!selectRows || selectRows.length === 0) {
      Modal.info({ title: '提示', content: '请先选择需要结算的申请单' });
      return;
    }
    // 结算申请单状态必须全部为待结算
    let statusMismatchRows = _.find(selectRows, (row) => {
      return row.settlementStatus != "NULL";
    });
    if (statusMismatchRows && Object.keys(statusMismatchRows).length != 0) {
      Modal.info({ title: '提示', content: '只有状态为「待结算」的申请单可以进行结算操作' });
      return;
    }
    // 结算单必须属于同一个财务账户
    let accountMismatchRows = _.find(selectRows, (row) => {
      return row.financialAccountId != selectRows[0].financialAccountId;
    });
    if (accountMismatchRows && Object.keys(accountMismatchRows).length != 0) {
      Modal.info({ title: '提示', content: '请选择「同一个用户」的结算申请单进行结算' });
      return;
    }
    // 确认是（付款|收款）结算
    let totalMoney = 0;
    _.each(selectRows, (row) => {
      if (row.settlementType === "RECEIVABLE") {
        totalMoney += row.settlementMoney;
      } else if (row.settlementType === "PAYABLE") {
        totalMoney -= row.settlementMoney;
      }
    })
    let doSettlementType = "";
    totalMoney > 0
      ? doSettlementType = "RECEIVABLE"
      : doSettlementType = "PAYABLE";
    dispatch({
      type: 'financialSettlementApply/doSettlement',
      payload: {
        selectRows: selectRows,
        doSettlementType: doSettlementType
      }
    });
  }

  const tabChange = (key) => {
    dispatch({
      type: 'financialSettlementApply/setCurrentTab',
      payload:key
    })
    dispatch({
      type: 'financialSettlementApply/query'
    })
  }

  return (
    <PageHeaderLayout title="财务结算" breadcrumbList={breadcrumbList}>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <OrderFilterUnExpand {...filterProps} />
          <div className={styles.tableListOperator}>
            {showButton('financialSettlementApply.settlement', resources, user) && <Button
              icon="calculator"
              type="primary"
              onClick={() => doSettlement(selectRows)}>
              结算
                        </Button>}
          </div>
          <Tabs onChange={tabChange} type="card" activeKey={currentType}>
            <TabPane tab="余额账户" key="SALES">
              <List {...listProps} />
            </TabPane>
            <TabPane tab="第三方账户" key="THIRD">
              <List {...listProps} />
            </TabPane>
            <TabPane tab="优惠券账户" key="COUPON">
              <List {...listProps} />
            </TabPane>
            <TabPane tab="提成账户" key="COMMISSION">
              <List {...listProps} />
            </TabPane>
          </Tabs>
        </div>
      </Card>
    </PageHeaderLayout>
  )
};

export default connect(({ financialSettlementApply, app, loading }) => ({ financialSettlementApply, app, loading }))(FinancialSettlementApplies)
